package io.cici.cc.mybatis.lite.executor;

import io.cici.cc.mybatis.lite.executor.resultset.ResultContextHandler;
import io.cici.cc.mybatis.lite.executor.statement.StatementHandler;
import io.cici.cc.mybatis.lite.mapping.MappedStatement;
import io.cici.cc.mybatis.lite.mapping.Sql;
import io.cici.cc.mybatis.lite.session.Configuration;
import io.cici.cc.mybatis.lite.transaction.Transaction;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collections;
import java.util.List;

public class SimpleExecutor extends BaseExecutor {

    public SimpleExecutor(Configuration configuration, Transaction transaction) {
        super(configuration, transaction);
    }

    @Override
    public int doUpdate(MappedStatement mappedStatement, Object parameter) throws SQLException {
        Statement statement = null;
        try {
            Configuration configuration = mappedStatement.getConfiguration();
            StatementHandler statementHandler = configuration.newStatementHandler(this, mappedStatement, parameter,
                    null, null);
            statement = prepareStatement(statementHandler);
            return statementHandler.update(statement);
        } finally {
            closeStatement(statement);
        }
    }

    @Override
    public <E> List<E> doQuery(MappedStatement mappedStatement, Object parameter,
                               ResultContextHandler resultContextHandler, Sql sql) throws SQLException {
        Statement statement = null;
        try {
            Configuration configuration = mappedStatement.getConfiguration();
            StatementHandler statementHandler = configuration.newStatementHandler(wrapper, mappedStatement, parameter,
                    resultContextHandler, sql);
            statement = prepareStatement(statementHandler);
            return statementHandler.query(statement, resultContextHandler);
        } finally {
            closeStatement(statement);
        }
    }

    @Override
    public List<BatchResult> doFlushStatements(boolean isRollback) {
        return Collections.emptyList();
    }

    private Statement prepareStatement(StatementHandler statementHandler) throws SQLException {
        Statement statement;
        Connection connection = getConnection();
        statement = statementHandler.prepare(connection);
        statementHandler.parameterize(statement);
        return statement;
    }

}
